package com.service.impl;

import com.bean.User;
import com.mapper.UserMapper;
import com.service.UserService;
import com.utils.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.getUserByUsername(username);
    }

    @Override
    public PageInfo<User> getAllUsers(int pageNum, int pageSize) {
        return getUsersByKeyword("", pageNum, pageSize);
    }

    @Override
    public User login(String username, String password) {
        return userMapper.getUserByUsernameAndPassword(username, password);
    }

    @Override
    public boolean register(User user) {
        // 检查用户名是否已存在
        if (getUserByUsername(user.getUsername()) != null) {
            return false;
        }
        int result = userMapper.insertUser(user);
        return result > 0;
    }

    @Override
    public boolean updateUser(User user) {
        int result = userMapper.updateUser(user);
        return result > 0;
    }

    @Override
    public boolean deleteUserById(Integer id) {
        int result = userMapper.deleteUserById(id);
        return result > 0;
    }

    @Override
    public PageInfo<User> getUsersByKeyword(String keyword, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<User> userList = userMapper.getUsersByKeyword(keyword, offset, pageSize);
        int total = userMapper.getCountByKeyword(keyword);
        return new PageInfo<>(pageNum, pageSize, total, userList);
    }
}